package com.jse;

import java.lang.System.Logger;
import java.time.Instant;
import java.util.ResourceBundle;

public class Log implements Logger {

	private final static Cache<String,Log> CACHE=new Cache<>(32);
	
	public Log() {this(Log.class);}
	public Log(Class<?> cls) {this(cls.getName());}
	public Log(String name) {this.name=name;}

	
	public static Log get(String name){Log log=CACHE.get(name);if(log==null) {log=new Log(name);CACHE.put(name, log);}return log;}
	public static Log get(Class<?> c){return get(c.getName());}
	public static Log get(){return get(Thread.currentThread().getStackTrace()[1].getClassName());}
	
	private String name;

	@Override
	public String getName() {return name;}

	@Override
	public boolean isLoggable(Level level) {return level.compareTo(Jse.LEVEL)>-1;}

	@Override
	public void log(Level level, ResourceBundle bundle, String msg, Throwable e) {
		if(!isLoggable(level))return;
		if(msg.charAt(0)=='-')System.out.println(msg);//不追加前缀
		else System.out.println("%s [%s] [%s] [%s] %s".formatted(Instant.now().toString().substring(0,23),
				level,Jse.name,name,msg));
		if(e!=null)e.printStackTrace();
	}

	@Override
	public void log(Level level, ResourceBundle bundle, String format, Object... params) {
		log(level,bundle,format.replace("{}","%s").formatted(params),(Throwable)null);
	}
	
	public void trace(String fmt,Object...args){log(Level.TRACE,null,fmt,args);}
	public void debug(String fmt,Object...args){log(Level.DEBUG,null,fmt,args);}
	public void info(String fmt,Object...args){log(Level.INFO,null,fmt,args);}
	public void warn(String fmt,Object...args){log(Level.WARNING,null,fmt,args);}
	public void error(String fmt,Object...args){log(Level.ERROR,null,fmt,args);}

	
	
	public static void main(String[] args) {
		System.out.println();
	}

}
